package aescryptoutil;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * @ClassName: AESUtil
 * @DESCRIPT: TODO AES加密/解密工具 (对称加密)
 * @AUTHOR: lemontree
 * @DATA: 2020/6/30 1:50 PM
 **/
public class AESUtil {

    /**
     * 密钥
     */
    public static final String KEY = "0123456789012345";

    /**
     * @param input
     * @param key
     * @return
     */
    public static String encrypt(String input, String key) {
        byte[] crypted = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, skey);
            crypted = cipher.doFinal(input.getBytes());
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return new String(Base64.encodeBase64(crypted));
    }

    /**
     * @param input
     * @param key
     * @return
     */
    public static String decrypt(String input, String key) {
        byte[] output = null;
        try {
            SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skey);
            output = cipher.doFinal(Base64.decodeBase64(input));
        } catch (Exception e) {
            System.out.println(e.toString());
        }
        return new String(output);
    }

    public static void main(String[] args) {
        String key = "1234567891234567";
        String data = "oh my gad";
        System.out.println("明文"+data);
        String encrypt = AESUtil.encrypt(data,key);
        System.out.println("加密后:"+encrypt);
        String decrypt = AESUtil.decrypt(encrypt,key);
        System.out.println("解密后:"+decrypt);
    }
}
